<template>
    <el-dialog v-model="open" title="添加管理员" width="500px">
        <el-form :model="formItem" label-width="auto">

            <el-form-item label="管理员姓名">
                <el-input v-model="formItem.name" />
            </el-form-item>
            <el-form-item label="管理员账号">
                <el-input v-model="formItem.account" />
            </el-form-item>
            <el-form-item label="管理员密码">
                <el-input type="password"  show-password v-model="formItem.password" />
            </el-form-item>
            <el-form-item label="角色">
             <el-select v-model="formItem.role">
                <el-option v-for="item in rolesData"
                :key="item._id" :label="item.name"
                :value="item._id"></el-option>
             </el-select>
            </el-form-item>


            <el-form-item label="管理员状态">
                <el-radio-group v-model="formItem.state">
                    <el-radio label="开启" :value="1"></el-radio>
                    <el-radio label="关闭" :value="0"></el-radio>
                </el-radio-group>
            </el-form-item>

         
        </el-form>

<template #footer>
  <el-button>取消</el-button>
  <el-button type="primary" @click="handleOk">确认</el-button>
</template>

    </el-dialog>
</template>

<script setup lang="ts">

import api from '@/api';
import { useFetchData } from '@/hooks/fetchData';
import { ElMessage} from 'element-plus';
import { onMounted, ref,watch } from 'vue'
import { AdminItem } from '@/api/modules/admins';
const open = ref(false)
const formItem=ref<AdminItem>({})
const {getRolesDataDataAsync,rolesData}=useFetchData()
const emit=defineEmits(['getAdminsData'])
onMounted(()=>{
    getRolesDataDataAsync();
})

watch(open,()=>{
    if(!open.value){
formItem.value={};

    }
})




//打开弹窗
const onOpenDialog=(row?:AdminItem)=>{
    open.value=true;
    if(row){
        formItem.value={
            ...row,
        role: (row.role as any)._id
    };
      
    }
}


const handleOk=()=>{
    if(formItem.value._id){
        handleUpdate();
    }else{
        handleAdd();
    }
   
}
const handleAdd=()=>{
    
    api.admins.add({
        ...formItem.value,
    }).then(res=>{
        console.log(res);
        if(res.code==200){
            ElMessage.success('角色新增成功');
            open.value=false;
            emit('getAdminsData');
        }else{
            ElMessage.error(res.message);
        }
    })
    
}

  const handleUpdate=()=>{
    api.admins.update({
        ...formItem.value,
    }).then(res=>{
        console.log(res);
        if(res.code==200){
            ElMessage.success('角色修改成功');
            open.value=false;
            emit('getAdminsData');
        }else{
            ElMessage.error(res.message);
        }
        
    })
  }









defineExpose({
    onOpenDialog
})



</script>

<style scoped></style>
